/**
 * Created by joy on 16/09/2017.
 */
import 'node-assist'
import Sqlite from './modules/Sqlite'
import Rest from './modules/Rest'
import CommonUtil from 'js-common-modules/lib/utils/CommonUtil'
import FileUtil from 'js-common-modules/lib/utils/FileUtil'
import init from './modules/init'

function saveAccounts () {
  logger.info('保存账户信息中...')
  const accountsFile = global['dirs']['temp'] + '/accounts.json'

  FileUtil.writeSync(accountsFile, accountHelper.accounts)
}

(async () => {
  await init()
  CommonUtil.onExiting(() => {
    // 持久化账户
    saveAccounts()
    process.exit(0)
  })
  const sqlite = new Sqlite(sqliteHelper)
  await sqlite.initTables()

  const rest = new Rest()
  await rest.listen(args['restPort'], args['restHost'])

  if (args['server']) {
    await peerHelper.startServer(socketServerHelper, args['syncPort'])
  }
  // 连接预定义节点
  for (let peer_ of args['peers']) {
    await peerHelper.connectPeer(peer_)
  }

  if (Object.keys(peerHelper.peers['client']).length > 0 || Object.keys(peerHelper.peers['server']).length > 0) {
    // 不需要主动同步，因为邻节点接收到新块后会广播给我，被动同步
    // peer.startSyncTimer()

    blockHelper.startGeneBlockTimer()
  }
})().catch((err) => {
  logger.error(err)
  global['sqliteHelper'] && global['sqliteHelper'].close().then(() => {
    process.exit(1)
  })
})



